<template>
  <BasicModal
    v-bind="$attrs"
    destroyOnClose
    @register="registerDrawer"
    showFooter
    title="方法定义"
    width="60%"
    @ok="handleSubmit"
  >
    <!--  <FormTitle text="基础设置" class="ml-4" /> -->
    <div class="FormEventFuncConfig flex">
      <div class="func-list">
        <div class="func-item active-fn"
          >自定义JS
          <BasicHelp class="mx-0.5" maxWidth="700px" :text="jsDataHelp" />
        </div>
      </div>
      <div class="func-config">
        <CodeEditor v-model:value="scriptText" :mode="MODE.JS" />
      </div>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, unref } from 'vue';
  import { CodeEditor, MODE } from '/@/components/CodeEditor';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { jsData, jsDataHelp } from '/@/views/config-center/model-design/components/consts';
  import BasicHelp from '/@/components/Basic/src/BasicHelp.vue';
  export default defineComponent({
    name: 'FormEventFuncConfig',
    components: { BasicModal, CodeEditor, BasicHelp },
    emits: ['success', 'register'],
    setup() {
      const { createMessage } = useMessage();
      const currentData = ref<Indexable>({});
      const isUp = ref<Boolean>(false);
      const scriptText = ref<string>('');

      const [registerDrawer, { setModalProps, closeModal }] = useModalInner(
        async (data: Indexable) => {
          setModalProps({ confirmLoading: false, defaultFullscreen: true });
          init(data);
        },
      );
      async function init({ record, isUpdate }: Indexable) {
        currentData.value = record;

        let jsText = jsData;
        if (isUpdate) {
          jsText = record.scriptText || jsData;
        }
        scriptText.value = jsText;
        isUp.value = isUpdate;
      }
      async function handleSubmit() {
        const value = unref(scriptText);
        if (isUp.value) {
          currentData.value.scriptText = value;
        } else {
          currentData.value.funcList.push({ scriptText: value, label: '自定义JS' });
        }

        createMessage.success('操作成功');
        closeModal();
      }
      return {
        registerDrawer,
        handleSubmit,
        MODE,
        jsDataHelp,
        scriptText,
      };
    },
  });
</script>
<style lang="less" scoped>
  .FormEventFuncConfig {
    min-height: 80vh;
  }

  .func-list {
    text-align: center;
    flex: 0 0 110px;

    padding: 12px;
    border: 1px solid #eee;

    .active-fn {
      color: @primary-color;
      cursor: pointer;
    }
  }

  .func-config {
    flex: 1;
    border: 1px solid #eee;
    margin-left: 16px;
  }
</style>
